package vn.edu.uit.wifi_transfering;

import java.io.IOException;

import android.app.Activity;
import android.app.Dialog;
import android.database.Cursor;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.Toast;

public class Configuration extends Activity {

	private static final int CREATE_CONNECT_SERVER = 1;

	Button btnBack;
	Button btnConnectServer;
	Button btnCreateSocket;
	Button btnStopSocket;	
	Button btnSendFile;
	GridView gridServers;
	DBConnection db;
	public String host = "";
	public int port = 0;

	TCPClient client;
	String[] listTemp;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.configure_layout);
		
		db = new DBConnection(this);
		
		gridServers = (GridView) findViewById(R.id.gridview);

		btnBack = (Button) findViewById(R.id.btnBack);
		btnConnectServer = (Button) findViewById(R.id.btnConnectServer);
		btnConnectServer.setOnClickListener(new View.OnClickListener() {

			public void onClick(View v) {
				showDialog(CREATE_CONNECT_SERVER);
			}
		});

		btnBack.setOnClickListener(new View.OnClickListener() {

			public void onClick(View v) {
				finish();
				
			}
		});
		
		btnSendFile = (Button) findViewById(R.id.btnSendFile);
		btnSendFile.setOnClickListener(new View.OnClickListener() {
			
			public void onClick(View v) {				
				try {
					client = new TCPClient(host, port, Configuration.this);
					client.connectServer();
					boolean accept = client.sendFileInfo();
					if (accept) {
						client.sendFile();
					}
				} catch (IOException e) {
					e.printStackTrace();
				} catch (ClassNotFoundException e) {
					e.printStackTrace();
				}
			}
		});
	}
	
	@Override
	protected void onResume() {
		super.onResume();
		//db = new DBConnection(this);
		db.open();
		Cursor c = db.getAllservers();
		if (c.moveToFirst()) {
			listTemp = new String[c.getCount()];
			int i = 0;
			do {
				listTemp[i] = c.getString(1);
				i++;
			}while(c.moveToNext());
			
			gridServers.setAdapter(new ServerAdapter(this, listTemp));
		}
		db.close();
	}

	@Override
	protected Dialog onCreateDialog(int id) {

		final Dialog dialog = new Dialog(Configuration.this);
		switch (id) {
		case CREATE_CONNECT_SERVER:
			dialog.setContentView(R.layout.connect_server_layout);
			dialog.setTitle("Configure to connect Server");
			dialog.setCancelable(false);

			final EditText etServerHost = (EditText) dialog
					.findViewById(R.id.etServerHost);
			final EditText etServerPort = (EditText) dialog
					.findViewById(R.id.etServerPort);
			final EditText etUsername = (EditText) dialog
					.findViewById(R.id.etUsername);
			final EditText etPassword = (EditText) dialog
					.findViewById(R.id.etPassword);
			final CheckBox chkAnonymous = (CheckBox) dialog
					.findViewById(R.id.chkAnonymous);

			chkAnonymous
					.setOnCheckedChangeListener(new OnCheckedChangeListener() {

						public void onCheckedChanged(CompoundButton buttonView,
								boolean isChecked) {
							// TODO Auto-generated method stub
							if (isChecked) {
								etUsername.setEnabled(false);
								etPassword.setEnabled(false);
							} else {
								etUsername.setEnabled(true);
								etPassword.setEnabled(true);
							}
						}
					});

			Button btnConnect = (Button) dialog.findViewById(R.id.btnConnect);
			btnConnect.setOnClickListener(new View.OnClickListener() {

				public void onClick(View v) {

					String host = etServerHost.getText().toString();
					String port = etServerPort.getText().toString();
					String username = etUsername.getText().toString();
					String password = etPassword.getText().toString();
					boolean checkAnonymous = chkAnonymous.isChecked();

					if (host.equals("")) {
						Toast.makeText(Configuration.this,
								"Please input Server's IP", Toast.LENGTH_SHORT)
								.show();
						return;
					}

					if (!checkHost(host)) {
						Toast.makeText(Configuration.this,
								"Server's Host is Invalid !!!",
								Toast.LENGTH_SHORT).show();
						return;
					}					

					if (checkExistsHost(host)) {
						Toast.makeText(Configuration.this,
								"Server's Host exists !!!",
								Toast.LENGTH_SHORT).show();
						return;
					}
					
					if (port.equals("")) {
						Toast.makeText(Configuration.this,
								"Please input Server's Port",
								Toast.LENGTH_SHORT).show();
						return;
					}

					if (!checkPort(Integer.parseInt(port))) {
						Toast.makeText(Configuration.this,
								"Server's Port is Invalid !!!",
								Toast.LENGTH_SHORT).show();
						return;
					}

					if (!checkAnonymous) {
						if (username.equals("")) {
							Toast.makeText(Configuration.this,
									"Please input Username to login",
									Toast.LENGTH_SHORT).show();
							return;
						}

						if (password.equals("")) {
							Toast.makeText(Configuration.this,
									"Please input Password to login",
									Toast.LENGTH_SHORT).show();
							return;
						}
					}

					try {
						int _ping = pingHost(host);
						if (_ping != 0) {
							Toast.makeText(Configuration.this,
									"Cannot find Server " + host + " !!!",
									Toast.LENGTH_SHORT).show();
							return;
						}

						client = new TCPClient(host, Integer.parseInt(port),
								Configuration.this);
						client.connectServer();

						if (client.isConnect == 1) {
							Toast.makeText(Configuration.this,
									"Connecting ServerSocket is OK",
									Toast.LENGTH_SHORT).show();
							Configuration.this.host = host;
							Configuration.this.port = Integer.parseInt(port);
							try {
								int res = client.loginServer(username, password,
										checkAnonymous);
								switch (res) {
								case 0:									
									Toast.makeText(getBaseContext(), "Chung thuc thanh cong", Toast.LENGTH_SHORT).show();
									db.open();
									if (checkAnonymous) {
										db.insertServer(host, Integer.parseInt(port), username, password, 1);
									} else {
										db.insertServer(host, Integer.parseInt(port), username, password, 0);
									}
									db.close();
									
									onResume();
									etServerHost.setText(null);
									etServerPort.setText(null);
									etUsername.setText(null);
									etPassword.setText(null);
									chkAnonymous.setChecked(false);
									dialog.dismiss();
									client.stop();
									break;
								case 1:
									Toast.makeText(getBaseContext(), "Truy cap server ko can tai khoan !!!", Toast.LENGTH_SHORT).show();
									client.stop();
									break;
								case 2:
									Toast.makeText(getBaseContext(), "Truy cap server can tai khoan ???", Toast.LENGTH_SHORT).show();
									client.stop();
									break;
								case 3:
									Toast.makeText(getBaseContext(), "Tai khoan dang nhap sai username hoac password.", Toast.LENGTH_SHORT).show();
									client.stop();
									break;
								}
							} catch (ClassNotFoundException e) {
								e.printStackTrace();
							}
						} else {
							Toast.makeText(Configuration.this,
									"Cannot connect ServerSocket.",
									Toast.LENGTH_SHORT).show();
						}
					} catch (IOException e) {
						e.printStackTrace();
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
				}
			});

			Button btnCancel = (Button) dialog.findViewById(R.id.btnCancel);
			btnCancel.setOnClickListener(new View.OnClickListener() {

				public void onClick(View v) {
					etServerHost.setText(null);
					etServerPort.setText(null);
					etUsername.setText(null);
					etPassword.setText(null);
					chkAnonymous.setChecked(false);
					dialog.dismiss();
				}
			});

			break;
		}
		return dialog;
	}

	protected boolean checkHost(String host) {
		host = host.replace(".", " ");
		String[] pieces = host.split(" ");

		if (pieces.length != 4) {
			return false;
		} else {
			for (int i = 0; i < pieces.length; i++) {
				if (pieces[i].equals(null) || pieces[i].equals("")) {
					return false;
				}

				if (Integer.parseInt(pieces[i]) < 0
						|| Integer.parseInt(pieces[i]) > 255) {
					return false;
				}
			}

			return true;
		}
	}
	
	protected boolean checkExistsHost(String host) {
		db.open();
		Cursor c = db.getAllservers();
		if (c.moveToFirst()) {
			do {
				if (host.equals(c.getString(1))) {
					db.close();
					return true;
				}
			}while(c.moveToNext());
			db.close();
			return false;
		} else {
			db.close();
			return false;
		}		
	}

	protected boolean checkPort(int port) {
		if (1024 < port && port <= 65536) {
			return true;
		}
		return false;
	}

	protected static int pingHost(String host) throws IOException,
			InterruptedException {
		Runtime runtime = Runtime.getRuntime();
		Process proc = runtime.exec("ping -c 1 " + host);
		proc.waitFor();
		int exit = proc.exitValue();
		return exit;
	}

}
